package com.cx.common.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
 * 线程池执行工具
 * 
 * @Author:cxy
 * @Date:2019/10/24 15:11
 */
public class ExecutorUtils {

	/** 线程池 */
	private final static ExecutorService executors;
	/** 日志 */
	private static Logger LOGGER = LoggerFactory.getLogger(ExecutorUtils.class);

	static {
		int poolSize = 2;// Runtime.getRuntime().availableProcessors() / 2 + 1;
		int poolMaxSize = Runtime.getRuntime().availableProcessors() * 2;
		executors = new ThreadPoolExecutor(poolSize, poolMaxSize, 60, TimeUnit.SECONDS,
				new LinkedBlockingQueue<Runnable>());
	}

	public static void shutdown() {
		executors.shutdown();
	}

	/**
	 * 运行线程runnable调用
	 * 
	 * @param runnable
	 */
	public static void run(Runnable runnable) {
		if (runnable == null) {
			throw new NullPointerException("线程runnable对象不能为空");
		}
		executors.execute(runnable);
	}

	/**
	 * 
	 * @param runnable
	 */
	public static Future<?> submit(Runnable runnable) {
		if (runnable == null) {
			throw new NullPointerException("线程runnable对象不能为空");
		}
		Future<?> future = executors.submit(runnable);
		return future;
	}

	/**
	 * 运行线程callable调用
	 * 
	 * @param runnable
	 */
	public static <T> T call(Callable<T> callable, TimeUnit timeUnit, int timeout) {
		if (callable == null) {
			throw new NullPointerException("线程callable对象不能为空");
		}
		Future<T> future = executors.submit(callable);
		try {
			return future != null ? future.get(timeout, timeUnit) : null;
		} catch (Exception e) {
			LOGGER.error("", e);
		}
		return null;
	}

}
